<template>
  <el-container>
    <div style="height:15%; width: 100%; padding-top: 1%;">
      <el-card class="box-card">
        <div class="clearfix">
          <span>{{ this.docName }}</span>
          <div style="float: right;display:flex;">
            <div v-for="(item, index) in list" :key="index">
              <div style="display:flex; flex-direction: column;">
                <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
                <span style="text-align:center">{{ item }}</span>
              </div>

            </div>

          </div>
        </div>
      </el-card>
    </div>
    <div style="border: 1px solid #ccc; margin-top: 10px; height: 80%;width: 100%;">
      <!-- 工具栏 -->
      <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
      <!-- 编辑器 -->
      <Editor style="height: 550px; overflow-y: hidden; background-color: lightgray;" :defaultConfig="editorConfig"
        v-model="html" @onChange="onChange" @onCreated="onCreated" />
    </div>
  </el-container>
</template>

<script>
//TODO 加入WebSocket 实现协同编辑 使用 pdf-free 实现队员本文章样式 使用Mongo作为储存
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { getDocContent } from '@/api/editOnline/edit'
import { getToken } from '@/utils/auth'
import { mapGetters } from 'vuex'

export default {
  name: 'MyEditor',
  components: { Editor, Toolbar },
  data() {
    return {
      editor: null,
      html: '<p>hello&nbsp;world</p>',
      docName: '',
      websocketUrl: process.env.VUE_APP_WS_API,
      socket: null,
      list: [],
      toolbarConfig: {
        // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
        excludeKeys: ['fullScreen'],
      },
      editorConfig: {
        placeholder: '请输入内容...',

        // 所有的菜单配置，都要在 MENU_CONF 属性下
        MENU_CONF: {
        }
      },
      interval: null,
      pointPos: 0,
    }
  },
  computed: {
    ...mapGetters([
      'realName'
    ])
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 【注意】一定要用 Object.seal() 否则会报错\

    },
    onChange(editor) {
      console.log(editor.children)
      // var element = document.activeElement;
      // var cursorPosition = element.selectionStart;
      // console.log(element,cursorPosition)
    },

    mousePosition(ev) {
    },

    //websocket 相关配置
    initWebSocket(docId) {
      if ("WebSocket" in window) {
        if (this.socket == null) {
          this.socket = new WebSocket(this.websocketUrl + "/" + docId + "/" + this.$store.state.user.userId, [getToken()])
        }
        this.socket.onopen = this.onOpen;
        this.socket.onclose = this.onClose;
        this.socket.onerror = this.onError;
        this.socket.onmessage = this.onMessage;
      }
    },
    onOpen() {
      console.log("webSocket connect successfully")
      // this.sendMsgPerTime()
      this.list.push(this.realName)
    },
    onClose(err) {
      console.log("webSocket closed")
      console.log(err)
    },
    onMessage(event) {

      const data = JSON.parse(event.data)
      let count = this.list.length === 0 ? -1 : this.list.findIndex(val => { return val === data.data.userId });
      console.log(data)
      if (data.code === 200) {
        if (count === -1) {
          if (typeof data.data.flag !== "undefined") {
            for (var x in data.data.users) {
              this.list.push(data.data.users[x])
            }
          } else {

            this.list.push(data.data.realName)

          }
        } else {
          // this.editor.setHtml(data.data.imgUrl) 
        }
      } else if (data.code === 404) {
        if (count !== -1) {
          this.list.splice(count, 1)
        }
      }

    },
    onError(e) {
      console.log("webSocket error: " + e)
      // this.stopInterval();
      this.stopSendMsg()
    },
    // sendMsgPerTime(){
    //   if(this.editor != null && this.socket != null){

    //     const that = this

    //     that.interval = setInterval(()=>{
    //       that.socket.send(that.editor.getHtml())
    //     },500)
    //   }
    // },
    // stopSendMsg(){
    //   if(this.interval != null){
    //     clearInterval(this.interval)
    //   }
    // }
  },
  mounted() {

    const docId = this.$route.params.id;

    if (typeof docId == 'undefined') {
      return;
    }

    const that = this;
    //初始化数据
    getDocContent(docId).then(res => {
      that.docName = res.data.uploadFileName;
      that.html = res.data.content
    })


    //建立websocket连接
    this.initWebSocket(docId);
  },
  beforeDestroy() {
    if (this.socket != null) {
      this.socket.close();
    }

    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁 editor ，重要！！！
  },
}
</script>
<style>
.el-container {
  display: block;
  margin-left: 1%;
  margin-right: 1%;
}

.w-e-text-container {
  background-color: lightgray !important;
}

.w-e-scroll {
  position: absolute;
  overflow-y: auto;
  background: white;
  width: 70%;
  left: 15%;
  margin-top: 1% !important;
}

input ::first-line {
  color: red;
}
</style>
<style src="@wangeditor/editor/dist/css/style.css"></style>